﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using umbraco.BasePages;
using System.Text;

namespace Designit.Umb.Newsletter.Custom.usercontrols.designit.newsletter
{
    public partial class NewsletterSettings : System.Web.UI.UserControl
    {
        public bool HasMenu { get; set; }
        public bool Installing { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        private XmlDocument _doc;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!HasMenu)
            {
                Panel1.hasMenu = false;
                ButtonSave.Visible = true;
            }
            if(Width > int.MinValue)
                Panel1.Width = Width;
            if (Height > int.MinValue)
                Panel1.Height = Height;


            if (!IsPostBack)
            {
                var mailSettings = Bll.MailSettings.Get();
                txtName.Text = mailSettings.SenderName;
                txtMail.Text = mailSettings.SenderMail;
                txtUserID.Text = mailSettings.MailServerUsername;
                txtPassword.Text = mailSettings.MailServerPassword;
                var timeZoneId = mailSettings.TimezoneId;
                txtSMTP.Text = mailSettings.SmtpServer;
                txtPort.Text = mailSettings.SmtpPort.ToString();
                authcheck.Checked = mailSettings.SmtpAuth;
                txtPOP3.Text = mailSettings.Pop3Server;
                txtPopPort.Text = mailSettings.Pop3Port.ToString();
                txtBounce.Text = mailSettings.BounceHandlerInterval.ToString();
                softBounceCheck.Checked = mailSettings.SoftBounceHandling;
                txttestMail.Text = mailSettings.TestMail;
                if (!string.IsNullOrEmpty(mailSettings.Domain))
                    txtServer.Text = mailSettings.Domain;
                else
                    txtServer.Text = Request.Url.Host;
                txtunsub.Text = mailSettings.UnsubscribePage;
                //txtconfirmUnsub.Text = xnode.Attributes[1].Value;
                var sbLocalSites = new StringBuilder();
                foreach (var analyticsSite in mailSettings.GoogleAnalyticsSites)
                {
                    sbLocalSites.AppendLine(analyticsSite);
                }
                txtLocalSites.Text = sbLocalSites.ToString();

                TimezoneList.Items.AddRange(Bll.Helper.GetTimezoneListItems(timeZoneId));
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var save = Panel1.Menu.NewImageButton();
            save.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            save.AlternateText = "Save";
            save.Click += save_Click;
        }

        void save_Click(object sender, ImageClickEventArgs e)
        {
            Save();
        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void Save()
        {
            var mailSettings = Bll.MailSettings.Get();
            mailSettings.SenderName = txtName.Text;
            mailSettings.SenderMail = txtMail.Text;
            mailSettings.MailServerUsername = txtUserID.Text;
            //check if new password has been typed
            if (txtPassword.Text.Length > 0)
                mailSettings.MailServerPassword = txtPassword.Text;
            mailSettings.TimezoneId = TimezoneList.SelectedItem.Value;
            mailSettings.SmtpServer = txtSMTP.Text;
            mailSettings.SmtpPort = string.IsNullOrEmpty(txtPort.Text) ? 25 : Convert.ToInt32(txtPort.Text);
            mailSettings.SmtpAuth = authcheck.Checked;
            mailSettings.Pop3Server = txtPOP3.Text;
            mailSettings.Pop3Port = string.IsNullOrEmpty(txtPopPort.Text) ? 110 : Convert.ToInt32(txtPopPort.Text);
            mailSettings.BounceHandlerInterval = string.IsNullOrEmpty(txtBounce.Text) ? 0 : Convert.ToInt32(txtBounce.Text);
            mailSettings.SoftBounceHandling = softBounceCheck.Checked;
            mailSettings.TestMail = txttestMail.Text;
            mailSettings.Domain = txtServer.Text;
            mailSettings.UnsubscribePage = txtunsub.Text;
            //mailSettings.ConfirmUnsubscribePage = txtconfirmUnsub.Text;
            var lines = txtLocalSites.Text.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
            mailSettings.GoogleAnalyticsSites = new string[lines.Count()];
            var i = 0;
            foreach (var line in lines)
            {
                mailSettings.GoogleAnalyticsSites[i] = line.Trim();
                i++;
            }
            mailSettings.Update();

            if (!Installing)
            {
                if (this.BindingContainer is BasePage)
                    ((BasePage) this.BindingContainer).ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.success,
                                                                                    "Mail settings saved", "");
            }
            else
            {
                if (this.BindingContainer is BasePage)
                    ((BasePage)this.BindingContainer).ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.success,
                                                                    "Package installed. Please log off and on again to see the section.", "");
            }
        }
    }
}